package ipower.studentworks.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.BeanUtils;

import ipower.studentworks.dao.GradeDao;
import ipower.studentworks.domain.Grade;
import ipower.studentworks.pageModel.GradeInfo;
import ipower.studentworks.service.GradeService;

/**
 * 年级服务实现类。
 * @author young。
 * @since 2013-11-17。
 * */
public class GradeServiceImpl extends DataServiceImpl<Grade, GradeInfo> implements GradeService {
	private static final long serialVersionUID = 1L;
	private GradeDao dao;
	@Override
	public void setGradeDao(GradeDao gradeDao) {
		this.dao = gradeDao;
	}

	@Override
	protected List<Grade> find(GradeInfo info) {
		String hql = "from Grade g where 1 = 1";
		Map<String, Object> parameters = new HashMap<>();
		hql = this.addWhere(info, hql, parameters);
		if(info.getSort() != null && !info.getSort().isEmpty() && info.getOrder() != null && !info.getOrder().isEmpty()){
			hql += " order by g."+ info.getSort()+ " "+ info.getOrder() + ",g.level,g.value";
		}
		return this.dao.find(hql, parameters, info.getPage(), info.getRows());
	}

	@Override
	protected GradeInfo changeModel(Grade data) {
		GradeInfo info = new GradeInfo();
		BeanUtils.copyProperties(data, info);
		return info;
	}

	@Override
	protected Long total(GradeInfo info) {
		String hql = "select count(*) from Grade g where 1 = 1";
		Map<String, Object> parameters = new HashMap<>();
		hql = this.addWhere(info, hql, parameters);
		return this.dao.count(hql, parameters);
	}

	@Override
	protected String addWhere(GradeInfo info, String hql,Map<String, Object> parameters) {
		if(info.getName() != null && !info.getName().isEmpty()){
			hql += " and (g.code like :name or g.name like :name or g.value like :name)";
			parameters.put("name", "%"+info.getName()+"%");
		}
		return hql;
	}

	@Override
	public GradeInfo update(GradeInfo info) {
		if(info != null){
			boolean isAdd = false;
			Grade data = (info.getId() == null || info.getId().isEmpty()) ?  null : this.dao.load(Grade.class, info.getId());
			if(data == null){
				info.setId(UUID.randomUUID().toString());
				isAdd = true;
				data = new Grade();
			}
			BeanUtils.copyProperties(info, data);
			if(isAdd)this.dao.save(data);
		}
		return info;
	}

	@Override
	public void delete(String[] ids) {
		if(ids == null || ids.length == 0) return;
		for(String id : ids){
			if(id == null || id.isEmpty()) continue;
			Grade g = this.dao.load(Grade.class, id);
			if(g != null){
				this.dao.delete(g);
			}
		}
	}

	@Override
	public List<Grade> loadAllGrades() {
		return this.dao.find("from Grade g", null, null, null);
	}
}